﻿
using Alipay.EasySDK.Factory;
using Alipay.EasySDK.Kernel;
using Alipay.EasySDK.Kernel.Util;
using Alipay.EasySDK.Payment.Page.Models;
using God.ShoppingWebApi.DTO;
using God.ShoppingWebApi.Entities;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KeYan.Service.API
{
    [Route("api/[controller]")]
    [ApiController]
    public class AliPayController : ControllerBase
    {
       
        private readonly IHttpContextAccessor _contextAccessor;
        public AliPayController(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }

        //直接测试用地址,记得改订单信息. https://localhost:44341/api/app/a-li-pay/pay?Subject=test1&outTradeNo=111111111112&totalAmount=500
        [HttpGet, Route("Pay")]
        public async void Pay([FromQuery] AliPay dto)
        {

            #region 1. 设置参数（全局只需设置一次）
            var config = new Config()
            {
                Protocol = "https",
                GatewayHost = "openapi.alipaydev.com",//"openapi.alipay.com",沙箱
                SignType = "RSA2",
                AppId = "2021000118680411",
                //请填写您的应用私钥
                MerchantPrivateKey = "MIIEpAIBAAKCAQEAnLLSrDwUehd/OOM7pZujwFBRzjIHM2hMwCVJSvEw/fdjd7CeIW8b9l2L4yeuXfL/qOOzt7gCooXMFPJNQevs9YzYwTcX5aozLmMdiSA3dxqlf/zgXbvi8tZQ/sAIbo7NC2FQND013npaGjm25DWmcoAj85vKojIr/fg0i1YZVXNqxBki8mx+qoCAABQ+3QrGnxGv8WMhPfLxgWBYrhmevy+0dy0NDnq8MlbTru2luysmC/GMgrQIVPqPdJC/LEloM0XlbeXLLvZwWFKUXKzYyFnHDEfxhFuus/NvuaXw1JXcD1IjN+Ow973u2PgBGL+8M12yewxMZAAJ5pWK9+YKcwIDAQABAoIBADy/err447tdZp3oQhR23SnOOZilfnMoiTCog9yA2sxqXu5k0zkE+SMuqu+aT5fuf7y64c5kkOju0+p+8QKQcyHSw6lMMYCA1i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UQG5sGjVElhbhc3d1/MsFTVW/bxBQyg==",
                //支付宝公钥
                AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhThc+dcWI+Ly2Nv82LVLqEP6CzUHiNRu7ORNXDuEOyAeUWFFNM36PoLfuVe3h9lxWu8Yrk4aWyRjuiRRV/gWzs36n9nW7qviV5KwXclgfatjjYOg1E+J+aSNf6qowrN0bD2xtPFy2r5HDq1+yT64Swwjs6s8Z+JlZXxXkrjtD6eDxaE7j6HvPXGVyYeiwVg7rd32jAHMhM2LPsvBNSdFnRMaBc83VilL1CGisupw53/kl8mBftmuXgLB+F3D7ttCRcCcRIaLZ91qQD5fUQUKU1fPbTZS4oVZw00PfX+o5xSTVlmJKRhjIvo2FbrE6L4xqFmvRV4DYbMawjWE6LdcbwIDAQAB",
                //异步回调地址
                NotifyUrl = "https://localhost:44310/api/AliPay/NotifyUrl",
            };
            Factory.SetOptions(config);
            #endregion
            try
            {
                // 2. 发起API调用（以创建当面付收款二维码为例）
                //TODO:实训标题和订单号及金额是从dto中取得
                AlipayTradePagePayResponse response = Factory.Payment.Page().Pay(dto.Money, dto.ShopName, dto.ShopNumber, "https://localhost:44310/api/AliPay/NotifyUrl");
                // 3. 处理响应或异常
                if (ResponseChecker.Success(response))
                {
                    //把返回的html直接变成网页显示
                    var data = Encoding.UTF8.GetBytes(response.Body);
                    _contextAccessor.HttpContext.Response.ContentType = "text/html";
                    await _contextAccessor.HttpContext.Response.Body.WriteAsync(data, 0, data.Length);
                }
                else
                {
                    Console.WriteLine("调用失败，原因：" + response.Body);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("调用遭遇异常，原因：" + ex.Message);
            }
        }
        [HttpGet, Route("ReturnUrl")]
        public string ReturnUrl([FromQuery] AliPayDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //if()先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update
                // var list = _context.ServeInfo.Where(o => o..ToString().Equals(dto.out_trade_no)).FirstOrDefault();
                //修改状态为支付成功

                // list.OrderInfoState = 30;

                //_service.UpdateAsync(list);

                return "success";
            }
            return "";
        }
        [HttpGet, Route("NotifyUrl")]
        public string NotifyUrl(AliPayDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update
                //再循环返回库存
                //update

                return "success";
            }
            return "";
        }
    }
}
